﻿Imports Microsoft.Owin.Security
Imports System
Imports System.Collections.Generic
Imports System.Globalization
Imports System.Linq
Imports System.Web

Partial Public Class OpenAuthProviders
    Inherits System.Web.UI.UserControl
    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If IsPostBack Then
            Dim provider = Request.Form("provider")
            If provider Is Nothing Then
                Return
            End If
            ' Request a redirect to the external login provider
            Dim redirectUrl As String = ResolveUrl([String].Format(CultureInfo.InvariantCulture, "~/Account/RegisterExternalLogin?{0}={1}&returnUrl={2}", ProviderNameKey, provider, ReturnUrl))
            Context.GetOwinContext().Authentication.Challenge(New AuthenticationProperties() With {.RedirectUrl = redirectUrl}, provider)
            Response.StatusCode = 401
            Response.[End]()
        End If
    End Sub

    Public Property ReturnUrl() As String
        Get
            Return m_ReturnUrl
        End Get
        Set(value As String)
            m_ReturnUrl = value
        End Set
    End Property
    Private m_ReturnUrl As String

    Public Function GetProviderNames() As IEnumerable(Of String)
        Return Context.GetOwinContext().Authentication.GetExternalAuthenticationTypes().[Select](Function(t) t.AuthenticationType)
    End Function

    Public Const ProviderNameKey As String = "providerName"
    Public Shared Function GetProviderNameFromRequest(request As HttpRequest) As String
        Return request(ProviderNameKey)
    End Function

    Private Shared Function IsLocalUrl(url As String) As Boolean
        Return Not String.IsNullOrEmpty(url) AndAlso ((url(0) = "/"c AndAlso (url.Length = 1 OrElse (url(1) <> "/"c AndAlso url(1) <> "\"c))) OrElse (url.Length > 1 AndAlso url(0) = "~"c AndAlso url(1) = "/"c))
    End Function

    Public Shared Sub RedirectToReturnUrl(returnUrl As String, response As HttpResponse)
        If Not [String].IsNullOrEmpty(returnUrl) AndAlso IsLocalUrl(returnUrl) Then
            response.Redirect(returnUrl)
        Else
            response.Redirect("~/")
        End If
    End Sub
End Class
